﻿using System.Threading;
using DM4;
using sscore;
using System;
using System.Collections.Generic;
using sscore.Utils;
using System.Text.RegularExpressions;
using System.IO;
using sscore.Requests;

namespace DC
{
    public class DC : ModuleBase
    {
        private readonly string _searchUrl;
        private readonly string _offenderLink;
        private readonly string _imageLink;
        private const string StateName = "DC";
        private ResultFile _imagesResultFile;

        public DC()
        {
            //initialize main system constants
            ModuleCode = "SO_DC";
            Description = "DC Sex Offenders";
            Version = "1.0";

            //for creating sessions
            StartParam = 0;
            StopParam = 1200;

            //initialize help 
            AddToHelp(DM4Consts.StartPosition, String.Format("{0}...{1}", StartParam, StopParam));
            AddToHelp(DM4Consts.EndPositon, String.Format("{0}...{1}", StartParam, StopParam));

            AddToHelp(DM4Consts.IsDownload, "true|false");
            AddToHelp(DM4Consts.IsDownloadImg, "true|false");
            AddToHelp(DM4Consts.InsertToDb, "false|true", "(Expected: servername, dbname)");
            AddToHelp(DM4Consts.ServerName, "");
            AddToHelp(DM4Consts.DbName, "");
            AddToHelp(DM4Consts.IsClearDb, "false|true");
            AddToHelp(DM4Consts.TestParam, "false|true");

            Rpm.Codepage = EncodingType.Windows1251;
            RootUrl = "http://sor.csosa.net/";
            _searchUrl = string.Format("{0}sor/public/publicSearch.asp", RootUrl);
            _offenderLink = string.Format("{0}sor/public/genDataSheet.asp?id={{0}}", RootUrl);
            _imageLink = string.Format("{0}sor/clientPics/WebSizePDID/{{0}}.jpg", RootUrl);
        }

        private void SetParametersDefaults()
        {
            Params.CreateBooleanParam(DM4Consts.IsDownload, true);
            Params.CreateBooleanParam(DM4Consts.IsDownloadImg, true);
            Params.CreateBooleanParam(DM4Consts.InsertToDb, false);
            Params.CreateBooleanParam(DM4Consts.IsClearDb, false);
            Params.CreateStringParam(DM4Consts.DbName, "");
            Params.CreateStringParam(DM4Consts.ServerName, "");
            Params.CreateIntegerParam(DM4Consts.StartPosition, StartParam);
            Params.CreateIntegerParam(DM4Consts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
            Params.CreateIntegerParam(DM4Consts.EndPositon, StopParam);
        }

        public override OperationResult Init(IDM4Core iCore, DmTaskParams param)
        {
            //use basic initialization sequence
            base.Init(iCore, param);

            SetParametersDefaults();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult Start()
        {
            DoWork();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult DoWork()
        {
            OperationResult or = new OperationResult { Result = DM4Consts.ErrorUnknown };

            if (!Ct.IsCancellationRequested)
            {
                WriteLog("Start parameters:", MessageType.Warning);
                foreach (KeyValuePair<string, string> kvp in Params.GetDictionary()) //get all existing parameters
                    WriteLog(String.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value), MessageType.Warning);

                if (Params.GetBooleanParam(DM4Consts.IsDownload))
                    Load();

                if (Params.GetBooleanParam(DM4Consts.InsertToDb))
                    if ((Params.GetStringParam(DM4Consts.DbName) == "") || (Params.GetStringParam(DM4Consts.ServerName) == ""))
                    {
                        or.Message = String.Format("{0} or {1} is empty", DM4Consts.DbName, DM4Consts.ServerName);
                        ResultCode = DM4Consts.SessionResultCodeError;
                        ResultMessage = or.Message;
                        UpdateStatus(DmConsts.Error);
                        WriteErrorLog(or.Message); //writting to error and session log   

                        return or;
                    }
                    else
                    {
                        //insert offenders to db 
                        UpdateStatus(DM4Consts.SessionInsertToDb);

                        Offenders.OffInsertToDatabase(StateName, Params.GetStringParam(DmConsts.DbName),
                             Params.GetStringParam(DmConsts.ServerName), ResultDir, Params.GetBooleanParam(DmConsts.IsClearDb),
                             WriteLog);

                    }

                //check if need abort task
                if (Ct.IsCancellationRequested)
                {
                    ResultCode = DM4Consts.SessionResultTerminateByUser;
                    ResultMessage = "Session terminated by user";
                    UpdateStatus(DM4Consts.SessionWait);
                    WriteLog("Session aborted by user", MessageType.Cool);
                }
                else
                {
                    UpdateProgress(1);
                    ResultCode = DM4Consts.SessionResultCodeOk;
                    ResultMessage = String.Format("Session complete, errors : {0}, records : {1}", TaskParams.ErrorCount, TaskParams.RecordCount);
                    UpdateStatus(DM4Consts.SessionComplete);
                    WriteLog("------------Finish----------------", MessageType.Cool);
                }
            }
            else
            {
                ResultCode = DM4Consts.SessionResultTerminateByUser;
                ResultMessage = "Session terminated by user";
                UpdateStatus(DM4Consts.SessionWait);
                WriteLog("Session aborted by user", MessageType.Cool);
            }


            return or;
        }

        private void Load()
        {
            string resultFileName = String.Format("{0}\\{1}.{2}", ResultDir, TaskParams.SessionId, DmConsts.ResultFilesExtension);
            bool workFlag = true;

            ResultFile = new ResultFile(resultFileName, OffendersResult.GetHeader());
            _imagesResultFile = new ResultFile(String.Format("{0}\\{1}_images.{2}", ResultDir, TaskParams.SessionId, DM4Consts.ResultFilesExtension), "FileName|FileUrl");
            try
            {
                while (workFlag)
                {
                    //рабочий цикл
                    string error;

                    try
                    {
                        error = "";  //Required!!  /*if (!String.IsNullOrEmpty(error)) --> restart thread; else --> download finished*/

                        WriteLog("Start download...");
                        Searching();
                    }
                    catch (Exception e)
                    {
                        error = e.Message;
                    }

                    if (!String.IsNullOrEmpty(error))
                    {
                        Thread.Sleep(30000);
                        WriteErrorLog(error);
                        WriteLog("Try continue work...", MessageType.Warning);
                    }
                    else
                    {
                        workFlag = false;  //все нормально откачало, заканчиваем работу
                    }
                }
            }
            finally
            {
                ResultFile.Close();
                _imagesResultFile.Close();
            }
        }

        private void GetCookies()
        {
            string html = GetRedirectRequest.ReturnCookies(_searchUrl, Rpm);
            CheckHtml(html);
            Rpm.Cookies = Rpm.Cookies.Replace("; path=/", "");
        }

        private string CheckHtml(string html)
        {
            if (string.IsNullOrEmpty(html))
                throw new Exception(DmConsts.ErrEmpty);

            if (RegExpr.IsMatch(html, @"(?si:Access Denied)"))
                throw new Exception("Site response: \"Access Denied\"");

            return html;
        }

        private void Searching()
        {
            if (Test)
            {
                Params.SetIntegerParam(DmConsts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
                Params.SetIntegerParam(DmConsts.EndPositon, Params.GetIntegerParam(DmConsts.StartPosition));
            }

            GetCookies();
            string html = PostRedirectRequest.RefererWithCookies(
                string.Format("{0}sor/public/publicMainReport2.asp", RootUrl),
                _searchUrl,
                "txtAlpha=&ID258=&ckViewAll=ON&txtPSA=&txtDistrict=&txtPSA1=&txtDistrict1=",
                Rpm);

            ParseResultPage(CheckHtml(html));
        }

        private void ParseResultPage(string html)
        {
            html = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(html.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));

            if (!RegExpr.IsMatch(html, @"(?si:Showing matches for the following criteria)"))
                throw new Exception(String.Format("Result page: {0}{1}{2}", DmConsts.ExcNeedRestart, Environment.NewLine, html));

            MatchCollection mc = RegExpr.ParseMatchCollection(html, @"(?si:<a target=""_blank"" href=""genDataSheet.asp\x3Fid=(.*?)"")");
            WriteLog(String.Format("found [{0}] matches", mc.Count));
            if (mc.Count == 0)
                throw new Exception(DmConsts.ExcNeedRestart + Environment.NewLine + html);

            List<string> list = new List<string>();

            foreach (Match matchLoc in mc)
                if (!list.Contains(matchLoc.Groups[1].Value))
                    list.Add(matchLoc.Groups[1].Value);

            WriteLog(String.Format("found [{0}] id[s]", list.Count));

            for (int i = Params.GetIntegerParam(DmConsts.LastPosition); i <= Params.GetIntegerParam(DmConsts.EndPositon); i++)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;

                if (i > (list.Count - 1))
                    break;

                Params.SetIntegerParam(DmConsts.LastPosition, i);
                UpdateProgress();
                string lookupKey = list[i];
                string offenderHtml = GetRedirectRequest.RefererReturnCookies(string.Format(_offenderLink, lookupKey), RootUrl, Rpm); ;

                WriteLog(String.Format("ParseOffender [{0}][{1}]", Params.GetIntegerParam(DmConsts.LastPosition), lookupKey));

                if (!RegExpr.IsMatch(offenderHtml, @"(?si:Sex Offender Registration Information)"))
                    throw new Exception("Offenders page:" + DmConsts.ExcNeedRestart);

                ParseOffender(offenderHtml, lookupKey);
                UpdateRecordCount(1);
            }
        }

        private void ParseOffender(string offenderHtml, string lookupKey)
        {
            //могут быть пустые страницы по ссылке, например
            //<a target="_blank" href="genDataSheet.asp?id=522-439">Bell,&nbsp;Lamont&nbsp;A</b></font></a><br>/
            offenderHtml = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(offenderHtml.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));
            using (OffendersResult or = new OffendersResult())
            {
                or.Source_State = StateName;
                or.offenderLink = string.Format(_offenderLink, lookupKey);
                or.Source_id = lookupKey;

                or.fullname = RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Name\s*:\s*</b>(.*?)</p>)").Trim();
                if (or.fullname.Contains("</td>"))
                    or.fullname = RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Name\s*:\s*</b>(.*?)</td>)").Trim();
                if (or.fullname.Contains("<p>"))
                    or.fullname = RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Name\s*:\s*</b>(.*?)<p>)").Trim();

                or.AKA = RegExpUtils.Parse(offenderHtml, @"(?si:Aliases\s*:\s*</b>(.*?)</td>)").Trim();
                or.Address = HtmlUtils.KillSpace(RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Home\s*Address\s*/\s*Residence\s*:\s*</b>(.*?)</td>)").Replace("<br>", "@"));
                or.waddress = HtmlUtils.KillSpace(RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Work\s*Address\s*:\s*</b>(.*?)</td>)").Replace("<br>", "@"));
                or.Address_date = HtmlUtils.KillSpace(RegExpUtils.Parse(offenderHtml, @"(?si:<b>\s*Date\s*of\s*Last\s*Verification\s*:\s*</b>(.*?)</p>)").Replace("<br>", "@"));
                or.Birthdate = RegExpUtils.Parse(offenderHtml, @"(?si:\s*Date of Birth\s*:\s*</b>(.*?)</p>)").Trim();
                or.eye_color = RegExpUtils.Parse(offenderHtml, @"(?si:Eyes\s*:\s*</b>(.*?)</p>)").Trim();
                or.hair_color = RegExpUtils.Parse(offenderHtml, @"(?si:Hair\s*:\s*</b>(.*?)</p>)").Trim();
                or.height = RegExpUtils.Parse(offenderHtml, @"(?si:Height\s*:\s*</b>(.*?)</p>)").Trim();
                or.weight = RegExpUtils.Parse(offenderHtml, @"(?si:Weight\s*:\s*</b>(.*?)</p>)").Trim();
                or.registered = RegExpUtils.Parse(offenderHtml, @"(?si:Date of Registration\s*:\s*</b>(.*?)</p>)").Trim();
                or.marks = RegExpUtils.Parse(offenderHtml, @"(?si:Identifying Marks\s*:\s*</b>(.*?)</p>)").Trim();
                if (or.marks.ToLower() == "None Reported".ToLower())
                    or.marks = "";

                MatchCollection mc = RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Offense of Conviction\s*:\s*</b>(.*?)<a)");
                if (mc.Count > 0) or.Crime += "Offense of Conviction;Date of Conviction;Case No;Place of Conviction;Class of Offense~";
                for (int i = 0; i < mc.Count; i++)
                {
                    try
                    {
                        or.Crime += RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Offense of Conviction\s*:\s*</b>(.*?)<a)")[i].Groups[1].Value.Trim() + ";";
                    }
                    catch { or.Crime += ";"; }
                    try
                    {
                        or.Crime += RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Date of Conviction\s*:\s*</b>(.*?)</p>)")[i].Groups[1].Value.Trim() + ";";
                    }
                    catch { or.Crime += ";"; }
                    try
                    {
                        or.Crime += RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Case No.\s*:\s*</b>(.*?)</td>)")[i].Groups[1].Value.Trim() + ";";
                    }
                    catch { or.Crime += ";"; }
                    try
                    {
                        or.Crime += RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Place of Conviction\s*:\s*</b>(.*?)</td>)")[i].Groups[1].Value.Trim() + ";";
                    }
                    catch { or.Crime += ";"; }
                    try
                    {
                        or.Crime += RegExpUtils.ParseMatchCollection(offenderHtml, @"(?si:Class of Offense\s*:\s*</b>(.*?)</td>)")[i].Groups[1].Value.Trim() + "~";
                    }
                    catch { or.Crime += "~"; }
                }

                string htmlImgUrl = String.Format("/clientPics/WebSizePDID/{0}.jpg", or.Source_id);
                if (Params.GetBooleanParam(DmConsts.IsDownloadImg) && offenderHtml.Contains(htmlImgUrl))
                {
                    or.Image_ID = Guid.NewGuid() + ".jpg";
                    or.ImageLink = string.Format(_imageLink, or.Source_id);
                    Offenders.DownloadImageWithExceptions(_imagesResultFile, String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID),
                        or.ImageLink, TaskParams.SessionId);
                }

                if (or.Image_ID != "" && !File.Exists(String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID)))
                    throw new Exception(DmConsts.ExcImgNotFound);

                ResultFile.Write(or.GetValues());
            }
        }

        private void UpdateProgress()
        {
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.LastPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.LastPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.LastPosition))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.LastPosition),
                    DmConsts.StartPosition, DmConsts.LastPosition));
            UpdateProgress(((double)(Params.GetIntegerParam(DmConsts.LastPosition) - Params.GetIntegerParam(DmConsts.StartPosition))) / (Params.GetIntegerParam(DmConsts.EndPositon) - Params.GetIntegerParam(DmConsts.StartPosition) + 1));
        }
    }
}
